package com.wanmait.happyheating.interceptor;

import com.wanmait.happyheating.pojo.Userinfo;
import com.wanmait.happyheating.service.UserinfoService;
import com.wanmait.happyheating.util.IgnoreToken;
import com.wanmait.happyheating.util.JWTUtils;
import com.wanmait.happyheating.util.UserinfoJWTUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
@Component
public class UserinfoInterceptor implements HandlerInterceptor
{
    @Resource
    UserinfoService userinfoService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception
    {
   if(handler instanceof HandlerInterceptor){
       return true;
   }
        HandlerMethod handlerMethod=(HandlerMethod)handler;
        Method method=handlerMethod.getMethod();
       if(method.isAnnotationPresent(IgnoreToken.class))
       {
           IgnoreToken ignoreToken = method.getAnnotation(IgnoreToken.class);
           if(ignoreToken.required()){
               return true;
           }
       }
       String token=request.getHeader("token");
       if(token.equals(null)){
           throw new Exception ("没有登录");
       }
       Integer id=Integer.parseInt(UserinfoJWTUtils.getAudience(token));
      Userinfo userinfo= userinfoService.getById(id);
      if(userinfo==null){
          throw new Exception("没有该用户");
      }
        JWTUtils.verifyToken(token,userinfo.getPass());
      request.setAttribute("userinfo",userinfo);
        return true;
    }

}
